﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;
using Runda.CMS.Common.Entity;

namespace Runda.CMS.Portal.ContractFollowUp
{
    public partial class WorkRegistList : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TaskType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.SalesService)));
                TaskType.Items.Add(new ListItem("--不限--", "0"));
                TaskType.SelectedValue = "0";
                employeeName.Text = base.CurrentUserEntity.UserName;
                
                BindList(1);
            }
        }
        
        private void BindList(int pageindex)
        {
            //List<SqlDbParameter> parms = new List<SqlDbParameter>();

            string Whereclause = "";
            //string Whereclause = " and (PerformPerson='" + CurrentUserID.ToString() + "' or PerformPerson in ( select UserID from Cms_Sys_UserDepartment where DepartmentID in (select DepartmentID from Cms_Sys_UserDepartment where UserID='" + CurrentUserID.ToString() + "')))";
            if (txtContractCodeBasic.Text.Trim() != "")
            {
                Whereclause += " and CustomerID in ( select CustomerID from vw_CustomerAllInfo where CustomerName like '%" + txtContractCodeBasic.Text.Trim() + "%' or  CustomerArea like '%" + txtContractCodeBasic.Text.Trim() + "%')";
            }

            if (this.txtSerialNum.Text.Trim() != "")
            {
                Whereclause += " and InstrumentSerialNum  like '%" + txtSerialNum.Text.Trim() + "%'";
            }

            if (this.txtinstrumentName.Text.Trim() != "")
            {
                Whereclause += " and InstrumentID in ( select InstrumentID from Cms_Wsm_InstrumentInfo where InstrumentName like '%" + txtinstrumentName.Text.Trim() + "%')";
            }

            if (TaskType.SelectedValue.ToString() != "0")
            {
                Whereclause += " and TaskType = " + TaskType.SelectedValue.ToString();
            }
            if (employeeName.Text.Trim() != "")
            {
                Whereclause += " and (PerformPerson  in (select userid from cms_sys_user where username ='" + employeeName.Text.Trim().ToString() + "') or Agent in (select userid from cms_sys_user where username = '" + employeeName.Text.Trim() + "'))";
            }

            if (listIsSystemAssign.SelectedValue != "-1") {
                Whereclause += " and IsSystemAssign = " + listIsSystemAssign.SelectedValue;
            }

            if (status.SelectedValue != "")
            {
                Whereclause += " and TaskStatus=" + status.SelectedValue;
            }
            if (ExpectEndDateFrom.SelectedDate != null) {
                Whereclause += " and ExpectEndDate>='" + ExpectEndDateFrom.SelectedDate.ToString() + "'";
            }
            if (ExpectEndDateTo.SelectedDate != null) {
                Whereclause += " and ExpectEndDate<='" + ExpectEndDateTo.SelectedDate.ToString() + "'";
            }
            int RecordCount = 0;
            List<WsmTaskRegisterEntity> list = new SysUserBll().GetAll<WsmTaskRegisterEntity>(Whereclause, "ExpectEndDate asc", AspNetPager1.PageSize, pageindex, out RecordCount);

            RepeaterUsers.DataSource = list;
            RepeaterUsers.DataBind();
            AspNetPager1.RecordCount = RecordCount;
        }

        protected void RepeaterUsers_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "refersh")
            {
                BindList(1);
            }
            if (e.CommandName == "complete")
            {
                Label RegisterID = RepeaterUsers.Items[e.Item.ItemIndex].FindControl("RegisterID") as Label;
                WsmTaskRegisterEntity entity = new SystemBll().Get<WsmTaskRegisterEntity>(new Guid(RegisterID.Text));
                List<WsmMaintainBillEntity> entitys = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID = '" + RegisterID.Text + "'");
                if (entitys == null || entitys.Count == 0)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('该注册单还未输入服务单信息,不能直接完成！');", true);
                    return;
                }
                
                entity.TaskStatus = 1;
                new SystemBll().Update(entity);
            }

            if (e.CommandName == "delete")
            {
                Label RegisterID = RepeaterUsers.Items[e.Item.ItemIndex].FindControl("RegisterID") as Label;
                string MaintainID = "";
                WsmTaskRegisterEntity entity = new SystemBll().Get<WsmTaskRegisterEntity>(new Guid(RegisterID.Text));
                WsmMaintainBillEntity maintainEntity = null;
                WsmInstrumentAssemblyEntity AssemblyEntity = null;
                WsmInstrumentRecordEntity RecordEntity = null;
                WsmAccessoryReplacementEntity ReplaceEntity = null;
                List<WsmMaintainBillEntity> entitymaintains = new SystemBll().GetAll<WsmMaintainBillEntity>(" and RegisterID = '" + RegisterID.Text + "'");
                if (entitymaintains != null && entitymaintains.Count > 0)
                {
                    MaintainID = entitymaintains[0].MaintainID.ToString();
                    maintainEntity = entitymaintains[0];
                }

                if (MaintainID != "")
                {
                    List<WsmInstrumentAssemblyEntity> entitAssemblys = new SystemBll().GetAll<WsmInstrumentAssemblyEntity>(" and MaintainID = '" + MaintainID + "'");
                    if (entitAssemblys != null && entitAssemblys.Count > 0)
                    {
                        AssemblyEntity = entitAssemblys[0];
                    }

                    List<WsmInstrumentRecordEntity> entityRecords = new SystemBll().GetAll<WsmInstrumentRecordEntity>(" and MaintainID = '" + MaintainID + "'");
                    if (entityRecords != null && entityRecords.Count > 0)
                    {
                        RecordEntity = entityRecords[0];
                    }

                    List<WsmAccessoryReplacementEntity> entitReplaces = new SystemBll().GetAll<WsmAccessoryReplacementEntity>(" and MaintainID = '" + MaintainID + "'");
                    if (entitReplaces != null && entitReplaces.Count > 0)
                    {
                        ReplaceEntity = entitReplaces[0];
                    }
                }
                SystemBll bll = new SystemBll();
                if (entity != null)
                {
                    bll.LogicDelete(entity);
                }
                if (maintainEntity != null)
                { bll.LogicDelete(maintainEntity); }
                if (AssemblyEntity != null)
                {
                    bll.LogicDelete(AssemblyEntity);
                }
                if (RecordEntity != null)
                {
                    bll.LogicDelete(RecordEntity);
                }
                if (ReplaceEntity != null)
                {
                    bll.LogicDelete(ReplaceEntity);
                }
                if (MaintainID != "")
                {
                    new StockBll().cancelAccessoryUsage(MaintainID);
                }
                //WsmMaintainBillEntity maintainEntity = entitymaintains[0];

                //if (entity.IsSystemAssign)
                //{
                //    ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('有系统生成的注册单不能删除！');", true);
                //    return;
                //}
                //else
                //{
                //    if (entitys == null || entitys.Count == 0)
                //    {
                //        new SystemBll().LogicDelete(entity);
                //    }
                //    else
                //    {
                //        ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('该注册单已存在工作内容,不能删除！');", true);
                //        return;
                //    }
                //}
            }
            BindList(1);
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList(AspNetPager1.CurrentPageIndex);
        }

        protected void btnRefersh_Click(object sender, EventArgs e)
        {
            BindList(AspNetPager1.CurrentPageIndex);
        } 

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindList(1);
        }

        protected void RepeaterUsers_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Label CustomerID = e.Item.FindControl("CustomerID") as Label;
                Label CustomerName = e.Item.FindControl("CustomerName") as Label;
                Label CustomerAddress = e.Item.FindControl("CustomerAddress") as Label;
                Label PerformPerson = e.Item.FindControl("PerformPerson") as Label;
                Label PerformPersonName = e.Item.FindControl("PerformPersonName") as Label;
                Label Agent = e.Item.FindControl("Agent") as Label;
                Label AgentName = e.Item.FindControl("AgentName") as Label;
                Label TaskType = e.Item.FindControl("TaskType") as Label;
                Label TaskTypeName = e.Item.FindControl("TaskTypeName") as Label;
                Label TaskStatus = e.Item.FindControl("TaskStatus") as Label;
                Label TaskStatusName = e.Item.FindControl("TaskStatusName") as Label;
                Label CustomerArea = e.Item.FindControl("CustomerArea") as Label;
                Label InstrumentID = e.Item.FindControl("InstrumentID") as Label;
                Label Instrumentname = e.Item.FindControl("Instrumentname") as Label;
                Label CreatedBy = e.Item.FindControl("CreatedBy") as Label;
                Label CreatedByName = e.Item.FindControl("CreatedByName") as Label;
                Label IsSystemAssign = e.Item.FindControl("IsSystemAssign") as Label;
                LinkButton ltnDel = e.Item.FindControl("ltnDel") as LinkButton;

                if (CustomerID != null)
                {
                    CtrtCustomerEntity entity = new SystemBll().Get<CtrtCustomerEntity>(new Guid(CustomerID.Text));
                    CustomerName.Text = entity.CustomerName;
                    CustomerName.ToolTip = entity.CustomerName;
                    //CustomerAddress.Text = entity.CustomerAddress;

                    if (Agent.Text.Trim() != "")
                    {
                        AgentName.Text = new SystemBll().Get<SysUserEntity>(new Guid(Agent.Text)).UserName;
                    }
                    if (CreatedBy.Text.Trim() != "")
                    {
                        CreatedByName.Text = new SystemBll().Get<SysUserEntity>(new Guid(CreatedBy.Text)).UserName;
                    }
                    if (PerformPerson.Text.Trim() != "")
                    {
                        PerformPersonName.Text = new SystemBll().Get<SysUserEntity>(new Guid(PerformPerson.Text)).UserName;
                    }
                    TaskTypeName.Text = EnumeratorHelper.GetFieldText((Enumerator.SalesService)Convert.ToInt32(TaskType.Text));
                    if (IsSystemAssign.Text == "False" && (TaskType.Text == "3" || TaskType.Text == "6" || TaskType.Text == "7")) { TaskTypeName.Text += "(应需)"; }
                    if (IsSystemAssign.Text == "True" && (TaskType.Text == "3" || TaskType.Text == "6" || TaskType.Text == "7")) { TaskTypeName.Text += "(计划)"; } 
                    TaskStatusName.Text = (TaskStatus.Text == "0" ? "未完成" : "已完成");


                    WsmCustomerExtensionEntity extensionEntity = new SystemBll().Get<WsmCustomerExtensionEntity>(new Guid(CustomerID.Text));
                    if(extensionEntity != null)
                    CustomerArea.Text = extensionEntity.CustomerArea;

                    WsmInstrumentInfoEntity insurment = new SystemBll().Get<WsmInstrumentInfoEntity>(new Guid(InstrumentID.Text));
                    if (insurment != null)
                    {
                        Instrumentname.Text = insurment.instrumentName;
                        Instrumentname.ToolTip = insurment.instrumentName;
                    }

                    ltnDel.Visible = false;
                    ltnDel.OnClientClick = "return OnDelConfirm();";

                    if (base.CheckUserHasFuction(1, "Func5114") || TaskStatus.Text == "0")
                    { ltnDel.Visible = true; }
                    
                }
            }
        }
    }
}
